1) Hide section edit links for protected pages
[lhc/web/wiklou.git] / includes / Article.php
1 <?
2 # Class representing a Wikipedia article and history.
3 # See design.doc for an overview.
4
5 class Article {
6 /* private */ var $mContent, $mContentLoaded;
7 /* private */ var $mUser, $mTimestamp, $mUserText;
8 /* private */ var $mCounter, $mComment, $mCountAdjustment;
9 /* private */ var $mMinorEdit, $mRedirectedFrom;
10 /* private */ var $mTouched, $mFileCache;
11
12 function Article() { $this->clear(); }
13
14 /* private */ function clear()
15 {
16 $this->mContentLoaded = false;
17 $this->mUser = $this->mCounter = -1; # Not loaded
18 $this->mRedirectedFrom = $this->mUserText =
19 $this->mTimestamp = $this->mComment = $this->mFileCache = "";
20 $this->mCountAdjustment = 0;
21 $this->mTouched = "19700101000000";
22 }
23
24 /* static */ function newFromID( $newid )
25 {
26 global $wgOut, $wgTitle, $wgArticle;
27 $a = new Article();
28 $n = Article::nameOf( $newid );
29
30 $wgTitle = Title::newFromDBkey( $n );
31 $wgTitle->resetArticleID( $newid );
32
33 return $a;
34 }
35
36 /* static */ function nameOf( $id )
37 {
38 $sql = "SELECT cur_namespace,cur_title FROM cur WHERE " .
39 "cur_id={$id}";
40 $res = wfQuery( $sql, "Article::nameOf" );
41 if ( 0 == wfNumRows( $res ) ) { return NULL; }
42
43 $s = wfFetchObject( $res );
44 $n = Title::makeName( $s->cur_namespace, $s->cur_title );
45 return $n;
46 }
47
48 # Note that getContent/loadContent may follow redirects if
49 # not told otherwise, and so may cause a change to wgTitle.
50
51 function getContent( $noredir = false )
52 {
53 global $action,$section,$count,$wgTitle; # From query string
54 wfProfileIn( "Article::getContent" );
55
56 if ( 0 == $this->getID() ) {
57 if ( "edit" == $action ) {
58
59 global $wgTitle;
60 return ""; # was "newarticletext", now moved above the box)
61
62
63 }
64 wfProfileOut();
65 return wfMsg( "noarticletext" );
66 } else {
67 $this->loadContent( $noredir );
68 wfProfileOut();
69
70 if(
71 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
72 ( $wgTitle->getNamespace() == Namespace::getTalk( Namespace::getUser()) ) &&
73 preg_match("/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/",$wgTitle->getText()) &&
74 $action=="view"
75 )
76 {
77 return $this->mContent . "\n" .wfMsg("anontalkpagetext"); }
78 else {
79 if($action=="edit") {
80 if($section!="") {
81
82 $secs=preg_split("/(^=+.*?=+)/m",
83 $this->mContent, -1,
84 PREG_SPLIT_DELIM_CAPTURE);
85 if($section==0) {
86 return trim($secs[0]);
87 } else {
88 return trim($secs[$section*2-1] . $secs[$section*2]);
89 }
90 }
91 }
92 return $this->mContent;
93 }
94 }
95 }
96
97 function loadContent( $noredir = false )
98 {
99 global $wgOut, $wgTitle;
100 global $oldid, $redirect; # From query
101
102 if ( $this->mContentLoaded ) return;
103 $fname = "Article::loadContent";
104
105 # Pre-fill content with error message so that if something
106 # fails we'll have something telling us what we intended.
107
108 $t = $wgTitle->getPrefixedText();
109 if ( $oldid ) { $t .= ",oldid={$oldid}"; }
110 if ( $redirect ) { $t .= ",redirect={$redirect}"; }
111 $this->mContent = str_replace( "$1", $t, wfMsg( "missingarticle" ) );
112
113 if ( ! $oldid ) { # Retrieve current version
114 $id = $this->getID();
115 if ( 0 == $id ) return;
116
117 $sql = "SELECT " .
118 "cur_text,cur_timestamp,cur_user,cur_counter,cur_restrictions,cur_touched " .
119 "FROM cur WHERE cur_id={$id}";
120 $res = wfQuery( $sql, $fname );
121 if ( 0 == wfNumRows( $res ) ) { return; }
122
123 $s = wfFetchObject( $res );
124
125 # If we got a redirect, follow it (unless we've been told
126 # not to by either the function parameter or the query
127
128 if ( ( "no" != $redirect ) && ( false == $noredir ) &&
129 ( preg_match( "/^#redirect/i", $s->cur_text ) ) ) {
130 if ( preg_match( "/\\[\\[([^\\]\\|]+)[\\]\\|]/",
131 $s->cur_text, $m ) ) {
132 $rt = Title::newFromText( $m[1] );
133
134 # Gotta hand redirects to special pages differently:
135 # Fill the HTTP response "Location" header and ignore
136 # the rest of the page we're on.
137
138 if ( $rt->getInterwiki() != "" ) {
139 $wgOut->redirect( $rt->getFullURL() ) ;
140 return;
141 }
142 if ( $rt->getNamespace() == Namespace::getSpecial() ) {
143 $wgOut->redirect( wfLocalUrl(
144 $rt->getPrefixedURL() ) );
145 return;
146 }
147 $rid = $rt->getArticleID();
148 if ( 0 != $rid ) {
149 $sql = "SELECT cur_text,cur_timestamp,cur_user," .
150 "cur_counter,cur_touched FROM cur WHERE cur_id={$rid}";
151 $res = wfQuery( $sql, $fname );
152
153 if ( 0 != wfNumRows( $res ) ) {
154 $this->mRedirectedFrom = $wgTitle->getPrefixedText();
155 $wgTitle = $rt;
156 $s = wfFetchObject( $res );
157 }
158 }
159 }
160 }
161 $this->mContent = $s->cur_text;
162 $this->mUser = $s->cur_user;
163 $this->mCounter = $s->cur_counter;
164 $this->mTimestamp = $s->cur_timestamp;
165 $this->mTouched = $s->cur_touched;
166 $wgTitle->mRestrictions = explode( ",", trim( $s->cur_restrictions ) );
167 $wgTitle->mRestrictionsLoaded = true;
168 wfFreeResult( $res );
169 } else { # oldid set, retrieve historical version
170 $sql = "SELECT old_text,old_timestamp,old_user FROM old " .
171 "WHERE old_id={$oldid}";
172 $res = wfQuery( $sql, $fname );
173 if ( 0 == wfNumRows( $res ) ) { return; }
174
175 $s = wfFetchObject( $res );
176 $this->mContent = $s->old_text;
177 $this->mUser = $s->old_user;
178 $this->mCounter = 0;
179 $this->mTimestamp = $s->old_timestamp;
180 wfFreeResult( $res );
181 }
182 $this->mContentLoaded = true;
183 }
184
185 function getID() { global $wgTitle; return $wgTitle->getArticleID(); }
186
187 function getCount()
188 {
189 if ( -1 == $this->mCounter ) {
190 $id = $this->getID();
191 $this->mCounter = wfGetSQL( "cur", "cur_counter", "cur_id={$id}" );
192 }
193 return $this->mCounter;
194 }
195
196 # Would the given text make this article a "good" article (i.e.,
197 # suitable for including in the article count)?
198
199 function isCountable( $text )
200 {
201 global $wgTitle, $wgUseCommaCount;
202
203 if ( 0 != $wgTitle->getNamespace() ) { return 0; }
204 if ( preg_match( "/^#redirect/i", $text ) ) { return 0; }
205 $token = ($wgUseCommaCount ? "," : "[[" );
206 if ( false === strstr( $text, $token ) ) { return 0; }
207 return 1;
208 }
209
210 # Load the field related to the last edit time of the article.
211 # This isn't necessary for all uses, so it's only done if needed.
212
213 /* private */ function loadLastEdit()
214 {
215 global $wgOut;
216 if ( -1 != $this->mUser ) return;
217
218 $sql = "SELECT cur_user,cur_user_text,cur_timestamp," .
219 "cur_comment,cur_minor_edit FROM cur WHERE " .
220 "cur_id=" . $this->getID();
221 $res = wfQuery( $sql, "Article::loadLastEdit" );
222
223 if ( wfNumRows( $res ) > 0 ) {
224 $s = wfFetchObject( $res );
225 $this->mUser = $s->cur_user;
226 $this->mUserText = $s->cur_user_text;
227 $this->mTimestamp = $s->cur_timestamp;
228 $this->mComment = $s->cur_comment;
229 $this->mMinorEdit = $s->cur_minor_edit;
230 }
231 }
232
233 function getTimestamp()
234 {
235 $this->loadLastEdit();
236 return $this->mTimestamp;
237 }
238
239 function getUser()
240 {
241 $this->loadLastEdit();
242 return $this->mUser;
243 }
244
245 function getUserText()
246 {
247 $this->loadLastEdit();
248 return $this->mUserText;
249 }
250
251 function getComment()
252 {
253 $this->loadLastEdit();
254 return $this->mComment;
255 }
256
257 function getMinorEdit()
258 {
259 $this->loadLastEdit();
260 return $this->mMinorEdit;
261 }
262
263 # This is the default action of the script: just view the page of
264 # the given title.
265
266 function view()
267 {
268 global $wgUser, $wgOut, $wgTitle, $wgLang;
269 global $oldid, $diff; # From query
270 global $wgLinkCache;
271 wfProfileIn( "Article::view" );
272
273 $wgOut->setArticleFlag( true );
274 $wgOut->setRobotpolicy( "index,follow" );
275
276 # If we got diff and oldid in the query, we want to see a
277 # diff page instead of the article.
278
279 if ( isset( $diff ) ) {
280 $wgOut->setPageTitle( $wgTitle->getPrefixedText() );
281 $de = new DifferenceEngine( $oldid, $diff );
282 $de->showDiffPage();
283 wfProfileOut();
284 return;
285 }
286 $text = $this->getContent(); # May change wgTitle!
287 $wgOut->setPageTitle( $wgTitle->getPrefixedText() );
288 $wgOut->setHTMLTitle( $wgTitle->getPrefixedText() .
289 " - " . wfMsg( "wikititlesuffix" ) );
290
291 # We're looking at an old revision
292
293 if ( $oldid ) {
294 $this->setOldSubtitle();
295 $wgOut->setRobotpolicy( "noindex,follow" );
296 }
297 if ( "" != $this->mRedirectedFrom ) {
298 $sk = $wgUser->getSkin();
299 $redir = $sk->makeKnownLink( $this->mRedirectedFrom, "",
300 "redirect=no" );
301 $s = str_replace( "$1", $redir, wfMsg( "redirectedfrom" ) );
302 $wgOut->setSubtitle( $s );
303 }
304 $wgOut->checkLastModified( $this->mTouched );
305 $this->tryFileCache();
306 $wgLinkCache->preFill( $wgTitle );
307 $wgOut->addWikiText( $text );
308
309 # If the article we've just shown is in the "Image" namespace,
310 # follow it with the history list and link list for the image
311 # it describes.
312
313 if ( Namespace::getImage() == $wgTitle->getNamespace() ) {
314 $this->imageHistory();
315 $this->imageLinks();
316 }
317 $this->viewUpdates();
318 wfProfileOut();
319 }
320
321 # This is the function that gets called for "action=edit".
322
323 function edit()
324 {
325 global $wgOut, $wgUser, $wgTitle;
326 global $wpTextbox1, $wpSummary, $wpSave, $wpPreview;
327 global $wpMinoredit, $wpEdittime, $wpTextbox2;
328
329 $fields = array( "wpTextbox1", "wpSummary", "wpTextbox2" );
330 wfCleanFormFields( $fields );
331
332 if ( ! $wgTitle->userCanEdit() ) {
333 $this->view();
334 return;
335 }
336 if ( $wgUser->isBlocked() ) {
337 $this->blockedIPpage();
338 return;
339 }
340 if ( wfReadOnly() ) {
341 if( isset( $wpSave ) or isset( $wpPreview ) ) {
342 $this->editForm( "preview" );
343 } else {
344 $wgOut->readOnlyPage();
345 }
346 return;
347 }
348 if ( $_SERVER['REQUEST_METHOD'] != "POST" ) unset( $wpSave );
349 if ( isset( $wpSave ) ) {
350 $this->editForm( "save" );
351 } else if ( isset( $wpPreview ) ) {
352 $this->editForm( "preview" );
353 } else { # First time through
354 $this->editForm( "initial" );
355 }
356 }
357
358 # Since there is only one text field on the edit form,
359 # pressing <enter> will cause the form to be submitted, but
360 # the submit button value won't appear in the query, so we
361 # Fake it here before going back to edit(). This is kind of
362 # ugly, but it helps some old URLs to still work.
363
364 function submit()
365 {
366 global $wpSave, $wpPreview;
367 if ( ! isset( $wpPreview ) ) { $wpSave = 1; }
368
369 $this->edit();
370 }
371
372 # The edit form is self-submitting, so that when things like
373 # preview and edit conflicts occur, we get the same form back
374 # with the extra stuff added. Only when the final submission
375 # is made and all is well do we actually save and redirect to
376 # the newly-edited page.
377
378 function editForm( $formtype )
379 {
380 global $wgOut, $wgUser, $wgTitle;
381 global $wpTextbox1, $wpSummary, $wpWatchthis;
382 global $wpSave, $wpPreview;
383 global $wpMinoredit, $wpEdittime, $wpTextbox2, $wpSection;
384 global $oldid, $redirect, $section;
385 global $wgLang;
386
387 if($wpSection) { $section=$wpSection; }
388
389 $sk = $wgUser->getSkin();
390 $isConflict = false;
391 $wpTextbox1 = rtrim ( $wpTextbox1 ) ; # To avoid text getting longer on each preview
392
393 if(!$wgTitle->getArticleID()) { # new article
394
395 $wgOut->addWikiText(wfmsg("newarticletext"));
396
397 }
398
399 # Attempt submission here. This will check for edit conflicts,
400 # and redundantly check for locked database, blocked IPs, etc.
401 # that edit() already checked just in case someone tries to sneak
402 # in the back door with a hand-edited submission URL.
403
404 if ( "save" == $formtype ) {
405 if ( $wgUser->isBlocked() ) {
406 $this->blockedIPpage();
407 return;
408 }
409 if ( wfReadOnly() ) {
410 $wgOut->readOnlyPage();
411 return;
412 }
413 # If article is new, insert it.
414
415 $aid = $wgTitle->getArticleID();
416 if ( 0 == $aid ) {
417 # we need to strip Windoze linebreaks because some browsers
418 # append them and the string comparison fails
419 if ( ( "" == $wpTextbox1 ) ||
420 ( wfMsg( "newarticletext" ) == rtrim( preg_replace("/\r/","",$wpTextbox1) ) ) ) {
421 $wgOut->redirect( wfLocalUrl(
422 $wgTitle->getPrefixedURL() ) );
423 return;
424 }
425 $this->mCountAdjustment = $this->isCountable( $wpTextbox1 );
426 $this->insertNewArticle( $wpTextbox1, $wpSummary, $wpMinoredit, $wpWatchthis );
427 return;
428 }
429 # Article exists. Check for edit conflict.
430
431 $this->clear(); # Force reload of dates, etc.
432 if ( $this->getTimestamp() != $wpEdittime ) { $isConflict = true; }
433 $u = $wgUser->getID();
434
435 # Supress edit conflict with self
436
437 if ( ( 0 != $u ) && ( $this->getUser() == $u ) ) {
438 $isConflict = false;
439 }
440 if ( ! $isConflict ) {
441 # All's well: update the article here
442 $this->updateArticle( $wpTextbox1, $wpSummary, $wpMinoredit, $wpWatchthis, $wpSection );
443 return;
444 }
445 }
446 # First time through: get contents, set time for conflict
447 # checking, etc.
448
449 if ( "initial" == $formtype ) {
450 $wpEdittime = $this->getTimestamp();
451 $wpTextbox1 = $this->getContent(true);
452 $wpSummary = "";
453 }
454 $wgOut->setRobotpolicy( "noindex,nofollow" );
455 $wgOut->setArticleFlag( false );
456
457 if ( $isConflict ) {
458 $s = str_replace( "$1", $wgTitle->getPrefixedText(),
459 wfMsg( "editconflict" ) );
460 $wgOut->setPageTitle( $s );
461 $wgOut->addHTML( wfMsg( "explainconflict" ) );
462
463 $wpTextbox2 = $wpTextbox1;
464 $wpTextbox1 = $this->getContent(true);
465 $wpEdittime = $this->getTimestamp();
466 } else {
467 $s = str_replace( "$1", $wgTitle->getPrefixedText(),
468 wfMsg( "editing" ) );
469
470 if($section!="") { $s.=wfMsg("sectionedit");}
471 $wgOut->setPageTitle( $s );
472 if ( $oldid ) {
473 $this->setOldSubtitle();
474 $wgOut->addHTML( wfMsg( "editingold" ) );
475 }
476 }
477
478 if( wfReadOnly() ) {
479 $wgOut->addHTML( "<strong>" .
480 wfMsg( "readonlywarning" ) .
481 "</strong>" );
482 }
483 if( $wgTitle->isProtected() ) {
484 $wgOut->addHTML( "<strong>" . wfMsg( "protectedpagewarning" ) .
485 "</strong><br />\n" );
486 }
487
488 $kblength = (int)(strlen( $wpTextbox1 ) / 1024);
489 if( $kblength > 29 ) {
490 $wgOut->addHTML( "<strong>" .
491 str_replace( '$1', $kblength , wfMsg( "longpagewarning" ) )
492 . "</strong>" );
493 }
494
495 $rows = $wgUser->getOption( "rows" );
496 $cols = $wgUser->getOption( "cols" );
497
498 $ew = $wgUser->getOption( "editwidth" );
499 if ( $ew ) $ew = " style=\"width:100%\"";
500 else $ew = "" ;
501
502 $q = "action=submit";
503 if ( "no" == $redirect ) { $q .= "&redirect=no"; }
504 $action = wfEscapeHTML( wfLocalUrl( $wgTitle->getPrefixedURL(), $q ) );
505
506 $summary = wfMsg( "summary" );
507 $minor = wfMsg( "minoredit" );
508 $watchthis = wfMsg ("watchthis");
509 $save = wfMsg( "savearticle" );
510 $prev = wfMsg( "showpreview" );
511
512 $cancel = $sk->makeKnownLink( $wgTitle->getPrefixedURL(),
513 wfMsg( "cancel" ) );
514 $edithelp = $sk->makeKnownLink( wfMsg( "edithelppage" ),
515 wfMsg( "edithelp" ) );
516 $copywarn = str_replace( "$1", $sk->makeKnownLink(
517 wfMsg( "copyrightpage" ) ), wfMsg( "copyrightwarning" ) );
518
519 $wpTextbox1 = wfEscapeHTML( $wpTextbox1 );
520 $wpTextbox2 = wfEscapeHTML( $wpTextbox2 );
521 $wpSummary = wfEscapeHTML( $wpSummary );
522
523 // activate checkboxes if user wants them to be always active
524 if (!$wpPreview && $wgUser->getOption("watchdefault")) $wpWatchthis=1;
525 if (!$wpPreview && $wgUser->getOption("minordefault")) $wpMinoredit=1;
526
527 // activate checkbox also if user is already watching the page,
528 // require wpWatchthis to be unset so that second condition is not
529 // checked unnecessarily
530 if (!$wpWatchthis && !$wpPreview && $wgTitle->userIsWatching()) $wpWatchthis=1;
531
532 if ( 0 != $wgUser->getID() ) {
533 $checkboxhtml=
534 "<input tabindex=3 type=checkbox value=1 name='wpMinoredit'".($wpMinoredit?" checked":"").">{$minor}".
535 "<input tabindex=4 type=checkbox name='wpWatchthis'".($wpWatchthis?" checked":"").">{$watchthis}<br>";
536
537 } else {
538 $checkboxhtml="";
539 }
540
541
542 if ( "preview" == $formtype) {
543
544 $previewhead="<h2>" . wfMsg( "preview" ) . "</h2>\n<p><large><center><font color=\"#cc0000\">" .
545 wfMsg( "note" ) . wfMsg( "previewnote" ) . "</font></center></large><P>\n";
546 if ( $isConflict ) {
547 $previewhead.="<h2>" . wfMsg( "previewconflict" ) .
548 "</h2>\n";
549 }
550 $previewtext = wfUnescapeHTML( $wpTextbox1 );
551
552 if($wgUser->getOption("previewontop")) {
553 $wgOut->addHTML($previewhead);
554 $wgOut->addWikiText( $this->preSaveTransform( $previewtext ) ."\n\n");
555 }
556 $wgOut->addHTML( "<br clear=\"all\" />\n" );
557 }
558 $wgOut->addHTML( "
559 <form id=\"editform\" name=\"editform\" method=\"post\" action=\"$action\"
560 enctype=\"application/x-www-form-urlencoded\">
561 <textarea tabindex=1 name=\"wpTextbox1\" rows={$rows}
562 cols={$cols}{$ew} wrap=\"virtual\">" .
563 $wgLang->recodeForEdit( $wpTextbox1 ) .
564 "
565 </textarea><br>
566 {$summary}: <input tabindex=2 type=text value=\"{$wpSummary}\"
567 name=\"wpSummary\" maxlength=200 size=60><br>
568 {$checkboxhtml}
569 <input tabindex=5 type=submit value=\"{$save}\" name=\"wpSave\">
570 <input tabindex=6 type=submit value=\"{$prev}\" name=\"wpPreview\">
571 <em>{$cancel}</em> | <em>{$edithelp}</em>
572 <br><br>{$copywarn}
573 <input type=hidden value=\"{$section}\" name=\"wpSection\">
574 <input type=hidden value=\"{$wpEdittime}\" name=\"wpEdittime\">\n" );
575
576 if ( $isConflict ) {
577 $wgOut->addHTML( "<h2>" . wfMsg( "yourdiff" ) . "</h2>\n" );
578 DifferenceEngine::showDiff( $wpTextbox2, $wpTextbox1,
579 wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
580
581 $wgOut->addHTML( "<h2>" . wfMsg( "yourtext" ) . "</h2>
582 <textarea tabindex=6 name=\"wpTextbox2\" rows={$rows} cols={$cols} wrap=virtual>"
583 . $wgLang->recodeForEdit( $wpTextbox2 ) .
584 "
585 </textarea>" );
586 }
587 $wgOut->addHTML( "</form>\n" );
588 if($formtype =="preview" && !$wgUser->getOption("previewontop")) {
589 $wgOut->addHTML($previewhead);
590 $wgOut->addWikiText( $this->preSaveTransform( $previewtext ) );
591 }
592
593 }
594
595 # Theoretically we could defer these whole insert and update
596 # functions for after display, but that's taking a big leap
597 # of faith, and we want to be able to report database
598 # errors at some point.
599
600 /* private */ function insertNewArticle( $text, $summary, $isminor, $watchthis )
601 {
602 global $wgOut, $wgUser, $wgTitle, $wgLinkCache;
603 $fname = "Article::insertNewArticle";
604
605 $ns = $wgTitle->getNamespace();
606 $ttl = $wgTitle->getDBkey();
607 $text = $this->preSaveTransform( $text );
608 if ( preg_match( "/^#redirect/i", $text ) ) { $redir = 1; }
609 else { $redir = 0; }
610
611 $now = wfTimestampNow();
612 $won = wfInvertTimestamp( $now );
613 wfSeedRandom();
614 $rand = mt_rand() / mt_getrandmax();
615 $sql = "INSERT INTO cur (cur_namespace,cur_title,cur_text," .
616 "cur_comment,cur_user,cur_timestamp,cur_minor_edit,cur_counter," .
617 "cur_restrictions,cur_user_text,cur_is_redirect," .
618 "cur_is_new,cur_random,cur_touched,inverse_timestamp) VALUES ({$ns},'" . wfStrencode( $ttl ) . "', '" .
619 wfStrencode( $text ) . "', '" .
620 wfStrencode( $summary ) . "', '" .
621 $wgUser->getID() . "', '{$now}', " .
622 ( $isminor ? 1 : 0 ) . ", 0, '', '" .
623 wfStrencode( $wgUser->getName() ) . "', $redir, 1, $rand, '{$now}', '{$won}')";
624 $res = wfQuery( $sql, $fname );
625
626 $newid = wfInsertId();
627 $wgTitle->resetArticleID( $newid );
628
629 $sql = "INSERT INTO recentchanges (rc_timestamp,rc_cur_time," .
630 "rc_namespace,rc_title,rc_new,rc_minor,rc_cur_id,rc_user," .
631 "rc_user_text,rc_comment,rc_this_oldid,rc_last_oldid,rc_bot) VALUES (" .
632 "'{$now}','{$now}',{$ns},'" . wfStrencode( $ttl ) . "',1," .
633 ( $isminor ? 1 : 0 ) . ",{$newid}," . $wgUser->getID() . ",'" .
634 wfStrencode( $wgUser->getName() ) . "','" .
635 wfStrencode( $summary ) . "',0,0," .
636 ( $wgUser->isBot() ? 1 : 0 ) . ")";
637 wfQuery( $sql, $fname );
638 if ($watchthis) {
639 if(!$wgTitle->userIsWatching()) $this->watch();
640 } else {
641 if ( $wgTitle->userIsWatching() ) {
642 $this->unwatch();
643 }
644 }
645
646 $this->showArticle( $text, wfMsg( "newarticle" ) );
647 }
648
649 function updateArticle( $text, $summary, $minor, $watchthis, $section )
650 {
651 global $wgOut, $wgUser, $wgTitle, $wgLinkCache;
652 global $wgDBtransactions;
653 $fname = "Article::updateArticle";
654
655 // insert updated section into old text if we have only edited part
656 // of the article
657 if ($section != "") {
658 $oldtext=$this->getContent();
659 $secs=preg_split("/(^=+.*?=+)/m",$oldtext,-1,PREG_SPLIT_DELIM_CAPTURE);
660 $secs[$section*2]=$text."\n\n"; // replace with edited
661 if($section) { $secs[$section*2-1]=""; } // erase old headline
662 $text=join("",$secs);
663 }
664 if ( $this->mMinorEdit ) { $me1 = 1; } else { $me1 = 0; }
665 if ( $minor ) { $me2 = 1; } else { $me2 = 0; }
666 if ( preg_match( "/^(#redirect[^\\n]+)/i", $text, $m ) ) {
667 $redir = 1;
668 $text = $m[1] . "\n"; # Remove all content but redirect
669 }
670 else { $redir = 0; }
671 $this->loadLastEdit();
672
673 $text = $this->preSaveTransform( $text );
674
675 # Update article, but only if changed.
676
677 if( $wgDBtransactions ) {
678 $sql = "BEGIN";
679 wfQuery( $sql );
680 }
681 $oldtext = $this->getContent( true );
682
683 if ( 0 != strcmp( $text, $oldtext ) ) {
684 $this->mCountAdjustment = $this->isCountable( $text )
685 - $this->isCountable( $oldtext );
686
687 $sql = "INSERT INTO old (old_namespace,old_title,old_text," .
688 "old_comment,old_user,old_user_text,old_timestamp," .
689 "old_minor_edit,inverse_timestamp) VALUES (" .
690 $wgTitle->getNamespace() . ", '" .
691 wfStrencode( $wgTitle->getDBkey() ) . "', '" .
692 wfStrencode( $oldtext ) . "', '" .
693 wfStrencode( $this->getComment() ) . "', " .
694 $this->getUser() . ", '" .
695 wfStrencode( $this->getUserText() ) . "', '" .
696 $this->getTimestamp() . "', " . $me1 . ", '" .
697 wfInvertTimestamp( $this->getTimestamp() ) . "')";
698 $res = wfQuery( $sql, $fname );
699 $oldid = wfInsertID( $res );
700
701 $now = wfTimestampNow();
702 $won = wfInvertTimestamp( $now );
703 $sql = "UPDATE cur SET cur_text='" . wfStrencode( $text ) .
704 "',cur_comment='" . wfStrencode( $summary ) .
705 "',cur_minor_edit={$me2}, cur_user=" . $wgUser->getID() .
706 ",cur_timestamp='{$now}',cur_user_text='" .
707 wfStrencode( $wgUser->getName() ) .
708 "',cur_is_redirect={$redir}, cur_is_new=0, cur_touched='{$now}', inverse_timestamp='{$won}' " .
709 "WHERE cur_id=" . $this->getID();
710 wfQuery( $sql, $fname );
711
712 $sql = "INSERT INTO recentchanges (rc_timestamp,rc_cur_time," .
713 "rc_namespace,rc_title,rc_new,rc_minor,rc_bot,rc_cur_id,rc_user," .
714 "rc_user_text,rc_comment,rc_this_oldid,rc_last_oldid) VALUES (" .
715 "'{$now}','{$now}'," . $wgTitle->getNamespace() . ",'" .
716 wfStrencode( $wgTitle->getDBkey() ) . "',0,{$me2}," .
717 ( $wgUser->isBot() ? 1 : 0 ) . "," .
718 $this->getID() . "," . $wgUser->getID() . ",'" .
719 wfStrencode( $wgUser->getName() ) . "','" .
720 wfStrencode( $summary ) . "',0,{$oldid})";
721 wfQuery( $sql, $fname );
722
723 $sql = "UPDATE recentchanges SET rc_this_oldid={$oldid} " .
724 "WHERE rc_namespace=" . $wgTitle->getNamespace() . " AND " .
725 "rc_title='" . wfStrencode( $wgTitle->getDBkey() ) . "' AND " .
726 "rc_timestamp='" . $this->getTimestamp() . "'";
727 wfQuery( $sql, $fname );
728
729 $sql = "UPDATE recentchanges SET rc_cur_time='{$now}' " .
730 "WHERE rc_cur_id=" . $this->getID();
731 wfQuery( $sql, $fname );
732 }
733 if( $wgDBtransactions ) {
734 $sql = "COMMIT";
735 wfQuery( $sql );
736 }
737
738 if ($watchthis) {
739 if (!$wgTitle->userIsWatching()) $this->watch();
740 } else {
741 if ( $wgTitle->userIsWatching() ) {
742 $this->unwatch();
743 }
744 }
745
746 $this->showArticle( $text, wfMsg( "updated" ) );
747 }
748
749 # After we've either updated or inserted the article, update
750 # the link tables and redirect to the new page.
751
752 function showArticle( $text, $subtitle )
753 {
754 global $wgOut, $wgTitle, $wgUser, $wgLinkCache;
755
756 $wgLinkCache = new LinkCache();
757 $wgOut->addWikiText( $text ); # Just to update links
758
759 $this->editUpdates( $text );
760 if( preg_match( "/^#redirect/i", $text ) )
761 $r = "redirect=no";
762 else
763 $r = "";
764 $wgOut->redirect( wfLocalUrl( $wgTitle->getPrefixedURL(), $r ) );
765 }
766
767 # If the page we've just displayed is in the "Image" namespace,
768 # we follow it with an upload history of the image and its usage.
769
770 function imageHistory()
771 {
772 global $wgUser, $wgOut, $wgLang, $wgTitle;
773 $fname = "Article::imageHistory";
774
775 $sql = "SELECT img_size,img_description,img_user," .
776 "img_user_text,img_timestamp FROM image WHERE " .
777 "img_name='" . wfStrencode( $wgTitle->getDBkey() ) . "'";
778 $res = wfQuery( $sql, $fname );
779
780 if ( 0 == wfNumRows( $res ) ) { return; }
781
782 $sk = $wgUser->getSkin();
783 $s = $sk->beginImageHistoryList();
784
785 $line = wfFetchObject( $res );
786 $s .= $sk->imageHistoryLine( true, $line->img_timestamp,
787 $wgTitle->getText(), $line->img_user,
788 $line->img_user_text, $line->img_size, $line->img_description );
789
790 $sql = "SELECT oi_size,oi_description,oi_user," .
791 "oi_user_text,oi_timestamp,oi_archive_name FROM oldimage WHERE " .
792 "oi_name='" . wfStrencode( $wgTitle->getDBkey() ) . "' " .
793 "ORDER BY oi_timestamp DESC";
794 $res = wfQuery( $sql, $fname );
795
796 while ( $line = wfFetchObject( $res ) ) {
797 $s .= $sk->imageHistoryLine( false, $line->oi_timestamp,
798 $line->oi_archive_name, $line->oi_user,
799 $line->oi_user_text, $line->oi_size, $line->oi_description );
800 }
801 $s .= $sk->endImageHistoryList();
802 $wgOut->addHTML( $s );
803 }
804
805 function imageLinks()
806 {
807 global $wgUser, $wgOut, $wgTitle;
808
809 $wgOut->addHTML( "<h2>" . wfMsg( "imagelinks" ) . "</h2>\n" );
810
811 $sql = "SELECT il_from FROM imagelinks WHERE il_to='" .
812 wfStrencode( $wgTitle->getDBkey() ) . "'";
813 $res = wfQuery( $sql, "Article::imageLinks" );
814
815 if ( 0 == wfNumRows( $res ) ) {
816 $wgOut->addHtml( "<p>" . wfMsg( "nolinkstoimage" ) . "\n" );
817 return;
818 }
819 $wgOut->addHTML( "<p>" . wfMsg( "linkstoimage" ) . "\n<ul>" );
820
821 $sk = $wgUser->getSkin();
822 while ( $s = wfFetchObject( $res ) ) {
823 $name = $s->il_from;
824 $link = $sk->makeKnownLink( $name, "" );
825 $wgOut->addHTML( "<li>{$link}</li>\n" );
826 }
827 $wgOut->addHTML( "</ul>\n" );
828 }
829
830 # Add this page to my watchlist
831
832 function watch()
833 {
834 global $wgUser, $wgTitle, $wgOut, $wgLang;
835 global $wgDeferredUpdateList;
836
837 if ( 0 == $wgUser->getID() ) {
838 $wgOut->errorpage( "watchnologin", "watchnologintext" );
839 return;
840 }
841 if ( wfReadOnly() ) {
842 $wgOut->readOnlyPage();
843 return;
844 }
845 $wgUser->addWatch( $wgTitle );
846
847 $wgOut->setPagetitle( wfMsg( "addedwatch" ) );
848 $wgOut->setRobotpolicy( "noindex,follow" );
849
850 $sk = $wgUser->getSkin() ;
851 $link = $sk->makeKnownLink ( $wgTitle->getPrefixedText() ) ;
852
853 $text = str_replace( "$1", $link ,
854 wfMsg( "addedwatchtext" ) );
855 $wgOut->addHTML( $text );
856
857 $up = new UserUpdate();
858 array_push( $wgDeferredUpdateList, $up );
859
860 $wgOut->returnToMain( false );
861 }
862
863 function unwatch()
864 {
865 global $wgUser, $wgTitle, $wgOut, $wgLang;
866 global $wgDeferredUpdateList;
867
868 if ( 0 == $wgUser->getID() ) {
869 $wgOut->errorpage( "watchnologin", "watchnologintext" );
870 return;
871 }
872 if ( wfReadOnly() ) {
873 $wgOut->readOnlyPage();
874 return;
875 }
876 $wgUser->removeWatch( $wgTitle );
877
878 $wgOut->setPagetitle( wfMsg( "removedwatch" ) );
879 $wgOut->setRobotpolicy( "noindex,follow" );
880
881 $sk = $wgUser->getSkin() ;
882 $link = $sk->makeKnownLink ( $wgTitle->getPrefixedText() ) ;
883
884 $text = str_replace( "$1", $link ,
885 wfMsg( "removedwatchtext" ) );
886 $wgOut->addHTML( $text );
887
888 $up = new UserUpdate();
889 array_push( $wgDeferredUpdateList, $up );
890
891 $wgOut->returnToMain( false );
892 }
893
894 # This shares a lot of issues (and code) with Recent Changes
895
896 function history()
897 {
898 global $wgUser, $wgOut, $wgLang, $wgTitle, $offset, $limit;
899
900 # If page hasn't changed, client can cache this
901
902 $wgOut->checkLastModified( $this->getTimestamp() );
903 wfProfileIn( "Article::history" );
904
905 $wgOut->setPageTitle( $wgTitle->getPRefixedText() );
906 $wgOut->setSubtitle( wfMsg( "revhistory" ) );
907 $wgOut->setArticleFlag( false );
908 $wgOut->setRobotpolicy( "noindex,nofollow" );
909
910 if( $wgTitle->getArticleID() == 0 ) {
911 $wgOut->addHTML( wfMsg( "nohistory" ) );
912 wfProfileOut();
913 return;
914 }
915
916 $offset = (int)$offset;
917 $limit = (int)$limit;
918 if( $limit == 0 ) $limit = 50;
919 $namespace = $wgTitle->getNamespace();
920 $title = $wgTitle->getText();
921 $sql = "SELECT old_id,old_user," .
922 "old_comment,old_user_text,old_timestamp,old_minor_edit ".
923 "FROM old USE INDEX (name_title_timestamp) " .
924 "WHERE old_namespace={$namespace} AND " .
925 "old_title='" . wfStrencode( $wgTitle->getDBkey() ) . "' " .
926 "ORDER BY inverse_timestamp LIMIT $offset, $limit";
927 $res = wfQuery( $sql, "Article::history" );
928
929 $revs = wfNumRows( $res );
930 if( $wgTitle->getArticleID() == 0 ) {
931 $wgOut->addHTML( wfMsg( "nohistory" ) );
932 wfProfileOut();
933 return;
934 }
935
936 $sk = $wgUser->getSkin();
937 $numbar = wfViewPrevNext(
938 $offset, $limit,
939 $wgTitle->getPrefixedText(),
940 "action=history" );
941 $s = $numbar;
942 $s .= $sk->beginHistoryList();
943
944 if($offset == 0 )
945 $s .= $sk->historyLine( $this->getTimestamp(), $this->getUser(),
946 $this->getUserText(), $namespace,
947 $title, 0, $this->getComment(),
948 ( $this->getMinorEdit() > 0 ) );
949
950 $revs = wfNumRows( $res );
951 while ( $line = wfFetchObject( $res ) ) {
952 $s .= $sk->historyLine( $line->old_timestamp, $line->old_user,
953 $line->old_user_text, $namespace,
954 $title, $line->old_id,
955 $line->old_comment, ( $line->old_minor_edit > 0 ) );
956 }
957 $s .= $sk->endHistoryList();
958 $s .= $numbar;
959 $wgOut->addHTML( $s );
960 wfProfileOut();
961 }
962
963 function protect()
964 {
965 global $wgUser, $wgOut, $wgTitle;
966
967 if ( ! $wgUser->isSysop() ) {
968 $wgOut->sysopRequired();
969 return;
970 }
971 if ( wfReadOnly() ) {
972 $wgOut->readOnlyPage();
973 return;
974 }
975 $id = $wgTitle->getArticleID();
976 if ( 0 == $id ) {
977 $wgOut->fatalEror( wfMsg( "badarticleerror" ) );
978 return;
979 }
980 $sql = "UPDATE cur SET cur_touched='" . wfTimestampNow() . "'," .
981 "cur_restrictions='sysop' WHERE cur_id={$id}";
982 wfQuery( $sql, "Article::protect" );
983
984 $wgOut->redirect( wfLocalUrl( $wgTitle->getPrefixedURL() ) );
985 }
986
987 function unprotect()
988 {
989 global $wgUser, $wgOut, $wgTitle;
990
991 if ( ! $wgUser->isSysop() ) {
992 $wgOut->sysopRequired();
993 return;
994 }
995 if ( wfReadOnly() ) {
996 $wgOut->readOnlyPage();
997 return;
998 }
999 $id = $wgTitle->getArticleID();
1000 if ( 0 == $id ) {
1001 $wgOut->fatalEror( wfMsg( "badarticleerror" ) );
1002 return;
1003 }
1004 $sql = "UPDATE cur SET cur_touched='" . wfTimestampNow() . "'," .
1005 "cur_restrictions='' WHERE cur_id={$id}";
1006 wfQuery( $sql, "Article::unprotect" );
1007
1008 $wgOut->redirect( wfLocalUrl( $wgTitle->getPrefixedURL() ) );
1009 }
1010
1011 function delete()
1012 {
1013 global $wgUser, $wgOut, $wgTitle;
1014 global $wpConfirm, $wpReason, $image, $oldimage;
1015
1016 # Anybody can delete old revisions of images; only sysops
1017 # can delete articles and current images
1018
1019 if ( ( ! $oldimage ) && ( ! $wgUser->isSysop() ) ) {
1020 $wgOut->sysopRequired();
1021 return;
1022 }
1023 if ( wfReadOnly() ) {
1024 $wgOut->readOnlyPage();
1025 return;
1026 }
1027
1028 # Better double-check that it hasn't been deleted yet!
1029 $wgOut->setPagetitle( wfMsg( "confirmdelete" ) );
1030 if ( $image ) {
1031 if ( "" == trim( $image ) ) {
1032 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
1033 return;
1034 }
1035 $sub = str_replace( "$1", $image, wfMsg( "deletesub" ) );
1036 } else {
1037
1038 if ( ( "" == trim( $wgTitle->getText() ) )
1039 or ( $wgTitle->getArticleId() == 0 ) ) {
1040 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
1041 return;
1042 }
1043 $sub = str_replace( "$1", $wgTitle->getPrefixedText(),
1044 wfMsg( "deletesub" ) );
1045
1046 # determine whether this page has earlier revisions
1047 # and insert a warning if it does
1048 # we select the text because it might be useful below
1049 $sql="SELECT old_text FROM old WHERE old_namespace=0 and old_title='" . wfStrencode($wgTitle->getPrefixedDBkey())."' ORDER BY inverse_timestamp LIMIT 1";
1050 $res=wfQuery($sql,$fname);
1051 if( ($old=wfFetchObject($res)) && !$wpConfirm ) {
1052 $skin=$wgUser->getSkin();
1053 $wgOut->addHTML("<B>".wfMsg("historywarning"));
1054 $wgOut->addHTML( $skin->historyLink() ."</B><P>");
1055 }
1056
1057 $sql="SELECT cur_text FROM cur WHERE cur_namespace=0 and cur_title='" . wfStrencode($wgTitle->getPrefixedDBkey())."'";
1058 $res=wfQuery($sql,$fname);
1059 if( ($s=wfFetchObject($res))) {
1060
1061 # if this is a mini-text, we can paste part of it into the deletion reason
1062
1063 #if this is empty, an earlier revision may contain "useful" text
1064 if($s->cur_text!="") {
1065 $text=$s->cur_text;
1066 } else {
1067 if($old) {
1068 $text=$old->old_text;
1069 $blanked=1;
1070 }
1071
1072 }
1073
1074 $length=strlen($text);
1075
1076 # this should not happen, since it is not possible to store an empty, new
1077 # page. Let's insert a standard text in case it does, though
1078 if($length==0 && !$wpReason) { $wpReason=wfmsg("exblank");}
1079
1080
1081 if($length < 500 && !$wpReason) {
1082
1083 # comment field=255, let's grep the first 150 to have some user
1084 # space left
1085 $text=substr($text,0,150);
1086 # let's strip out newlines and HTML tags
1087 $text=preg_replace("/\"/","'",$text);
1088 $text=preg_replace("/\</","&lt;",$text);
1089 $text=preg_replace("/\>/","&gt;",$text);
1090 $text=preg_replace("/[\n\r]/","",$text);
1091 if(!$blanked) {
1092 $wpReason=wfMsg("excontent"). " '".$text;
1093 } else {
1094 $wpReason=wfMsg("exbeforeblank") . " '".$text;
1095 }
1096 if($length>150) { $wpReason .= "..."; } # we've only pasted part of the text
1097 $wpReason.="'";
1098 }
1099 }
1100
1101 }
1102
1103 # Likewise, deleting old images doesn't require confirmation
1104 if ( $oldimage || 1 == $wpConfirm ) {
1105 $this->doDelete();
1106 return;
1107 }
1108
1109 $wgOut->setSubtitle( $sub );
1110 $wgOut->setRobotpolicy( "noindex,nofollow" );
1111 $wgOut->addWikiText( wfMsg( "confirmdeletetext" ) );
1112
1113 $t = $wgTitle->getPrefixedURL();
1114 $q = "action=delete";
1115
1116 if ( $image ) {
1117 $q .= "&image={$image}";
1118 } else if ( $oldimage ) {
1119 $q .= "&oldimage={$oldimage}";
1120 } else {
1121 $q .= "&title={$t}";
1122 }
1123 $formaction = wfEscapeHTML( wfLocalUrl( "", $q ) );
1124 $confirm = wfMsg( "confirm" );
1125 $check = wfMsg( "confirmcheck" );
1126 $delcom = wfMsg( "deletecomment" );
1127
1128 $wgOut->addHTML( "
1129 <form id=\"deleteconfirm\" method=\"post\" action=\"{$formaction}\">
1130 <table border=0><tr><td align=right>
1131 {$delcom}:</td><td align=left>
1132 <input type=text size=60 name=\"wpReason\" value=\"{$wpReason}\">
1133 </td></tr><tr><td>&nbsp;</td></tr>
1134 <tr><td align=right>
1135 <input type=checkbox name=\"wpConfirm\" value='1'>
1136 </td><td>{$check}</td>
1137 </tr><tr><td>&nbsp;</td><td>
1138 <input type=submit name=\"wpConfirmB\" value=\"{$confirm}\">
1139 </td></tr></table></form>\n" );
1140
1141 $wgOut->returnToMain( false );
1142 }
1143
1144 function doDelete()
1145 {
1146 global $wgOut, $wgTitle, $wgUser, $wgLang;
1147 global $image, $oldimage, $wpReason;
1148 $fname = "Article::doDelete";
1149
1150 if ( $image ) {
1151 $dest = wfImageDir( $image );
1152 $archive = wfImageDir( $image );
1153 if ( ! unlink( "{$dest}/{$image}" ) ) {
1154 $wgOut->fileDeleteError( "{$dest}/{$image}" );
1155 return;
1156 }
1157 $sql = "DELETE FROM image WHERE img_name='" .
1158 wfStrencode( $image ) . "'";
1159 wfQuery( $sql, $fname );
1160
1161 $sql = "SELECT oi_archive_name FROM oldimage WHERE oi_name='" .
1162 wfStrencode( $image ) . "'";
1163 $res = wfQuery( $sql, $fname );
1164
1165 while ( $s = wfFetchObject( $res ) ) {
1166 $this->doDeleteOldImage( $s->oi_archive_name );
1167 }
1168 $sql = "DELETE FROM oldimage WHERE oi_name='" .
1169 wfStrencode( $image ) . "'";
1170 wfQuery( $sql, $fname );
1171
1172 # Image itself is now gone, and database is cleaned.
1173 # Now we remove the image description page.
1174
1175 $nt = Title::newFromText( $wgLang->getNsText( Namespace::getImage() ) . ":" . $image );
1176 $this->doDeleteArticle( $nt );
1177
1178 $deleted = $image;
1179 } else if ( $oldimage ) {
1180 $this->doDeleteOldImage( $oldimage );
1181 $sql = "DELETE FROM oldimage WHERE oi_archive_name='" .
1182 wfStrencode( $oldimage ) . "'";
1183 wfQuery( $sql, $fname );
1184
1185 $deleted = $oldimage;
1186 } else {
1187 $this->doDeleteArticle( $wgTitle );
1188 $deleted = $wgTitle->getPrefixedText();
1189 }
1190 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
1191 $wgOut->setRobotpolicy( "noindex,nofollow" );
1192
1193 $sk = $wgUser->getSkin();
1194 $loglink = $sk->makeKnownLink( $wgLang->getNsText(
1195 Namespace::getWikipedia() ) .
1196 ":" . wfMsg( "dellogpage" ), wfMsg( "deletionlog" ) );
1197
1198 $text = str_replace( "$1" , $deleted, wfMsg( "deletedtext" ) );
1199 $text = str_replace( "$2", $loglink, $text );
1200
1201 $wgOut->addHTML( "<p>" . $text );
1202 $wgOut->returnToMain( false );
1203 }
1204
1205 function doDeleteOldImage( $oldimage )
1206 {
1207 global $wgOut;
1208
1209 $name = substr( $oldimage, 15 );
1210 $archive = wfImageArchiveDir( $name );
1211 if ( ! unlink( "{$archive}/{$oldimage}" ) ) {
1212 $wgOut->fileDeleteError( "{$archive}/{$oldimage}" );
1213 }
1214 }
1215
1216 function doDeleteArticle( $title )
1217 {
1218 global $wgUser, $wgOut, $wgLang, $wpReason, $wgTitle, $wgDeferredUpdateList;
1219
1220 $fname = "Article::doDeleteArticle";
1221 $ns = $title->getNamespace();
1222 $t = wfStrencode( $title->getDBkey() );
1223 $id = $title->getArticleID();
1224
1225 if ( "" == $t ) {
1226 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
1227 return;
1228 }
1229
1230 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1231 array_push( $wgDeferredUpdateList, $u );
1232
1233 # Move article and history to the "archive" table
1234 $sql = "INSERT INTO archive (ar_namespace,ar_title,ar_text," .
1235 "ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit," .
1236 "ar_flags) SELECT cur_namespace,cur_title,cur_text,cur_comment," .
1237 "cur_user,cur_user_text,cur_timestamp,cur_minor_edit,0 FROM cur " .
1238 "WHERE cur_namespace={$ns} AND cur_title='{$t}'";
1239 wfQuery( $sql, $fname );
1240
1241 $sql = "INSERT INTO archive (ar_namespace,ar_title,ar_text," .
1242 "ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit," .
1243 "ar_flags) SELECT old_namespace,old_title,old_text,old_comment," .
1244 "old_user,old_user_text,old_timestamp,old_minor_edit,old_flags " .
1245 "FROM old WHERE old_namespace={$ns} AND old_title='{$t}'";
1246 wfQuery( $sql, $fname );
1247
1248 # Now that it's safely backed up, delete it
1249
1250 $sql = "DELETE FROM cur WHERE cur_namespace={$ns} AND " .
1251 "cur_title='{$t}'";
1252 wfQuery( $sql, $fname );
1253
1254 $sql = "DELETE FROM old WHERE old_namespace={$ns} AND " .
1255 "old_title='{$t}'";
1256 wfQuery( $sql, $fname );
1257
1258 $sql = "DELETE FROM recentchanges WHERE rc_namespace={$ns} AND " .
1259 "rc_title='{$t}'";
1260 wfQuery( $sql, $fname );
1261
1262 # Finally, clean up the link tables
1263
1264 if ( 0 != $id ) {
1265 $t = wfStrencode( $title->getPrefixedDBkey() );
1266 $sql = "SELECT l_from FROM links WHERE l_to={$id}";
1267 $res = wfQuery( $sql, $fname );
1268
1269 $sql = "INSERT INTO brokenlinks (bl_from,bl_to) VALUES ";
1270 $now = wfTimestampNow();
1271 $sql2 = "UPDATE cur SET cur_touched='{$now}' WHERE cur_id IN (";
1272 $first = true;
1273
1274 while ( $s = wfFetchObject( $res ) ) {
1275 $nt = Title::newFromDBkey( $s->l_from );
1276 $lid = $nt->getArticleID();
1277
1278 if ( ! $first ) { $sql .= ","; $sql2 .= ","; }
1279 $first = false;
1280 $sql .= "({$lid},'{$t}')";
1281 $sql2 .= "{$lid}";
1282 }
1283 $sql2 .= ")";
1284 if ( ! $first ) {
1285 wfQuery( $sql, $fname );
1286 wfQuery( $sql2, $fname );
1287 }
1288 wfFreeResult( $res );
1289
1290 $sql = "DELETE FROM links WHERE l_to={$id}";
1291 wfQuery( $sql, $fname );
1292
1293 $sql = "DELETE FROM links WHERE l_from='{$t}'";
1294 wfQuery( $sql, $fname );
1295
1296 $sql = "DELETE FROM imagelinks WHERE il_from='{$t}'";
1297 wfQuery( $sql, $fname );
1298
1299 $sql = "DELETE FROM brokenlinks WHERE bl_from={$id}";
1300 wfQuery( $sql, $fname );
1301 }
1302
1303 $log = new LogPage( wfMsg( "dellogpage" ), wfMsg( "dellogpagetext" ) );
1304 $art = $title->getPrefixedText();
1305 $wpReason = wfCleanQueryVar( $wpReason );
1306 $log->addEntry( str_replace( "$1", $art, wfMsg( "deletedarticle" ) ), $wpReason );
1307
1308 # Clear the cached article id so the interface doesn't act like we exist
1309 $wgTitle->resetArticleID( 0 );
1310 $wgTitle->mArticleID = 0;
1311 }
1312
1313 function revert()
1314 {
1315 global $wgOut;
1316 global $oldimage;
1317
1318 if ( strlen( $oldimage ) < 16 ) {
1319 $wgOut->unexpectedValueError( "oldimage", $oldimage );
1320 return;
1321 }
1322 if ( wfReadOnly() ) {
1323 $wgOut->readOnlyPage();
1324 return;
1325 }
1326 $name = substr( $oldimage, 15 );
1327
1328 $dest = wfImageDir( $name );
1329 $archive = wfImageArchiveDir( $name );
1330 $curfile = "{$dest}/{$name}";
1331
1332 if ( ! is_file( $curfile ) ) {
1333 $wgOut->fileNotFoundError( $curfile );
1334 return;
1335 }
1336 $oldver = wfTimestampNow() . "!{$name}";
1337 $size = wfGetSQL( "oldimage", "oi_size", "oi_archive_name='" .
1338 wfStrencode( $oldimage ) . "'" );
1339
1340 if ( ! rename( $curfile, "${archive}/{$oldver}" ) ) {
1341 $wgOut->fileRenameError( $curfile, "${archive}/{$oldver}" );
1342 return;
1343 }
1344 if ( ! copy( "{$archive}/{$oldimage}", $curfile ) ) {
1345 $wgOut->fileCopyError( "${archive}/{$oldimage}", $curfile );
1346 }
1347 wfRecordUpload( $name, $oldver, $size, wfMsg( "reverted" ) );
1348
1349 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
1350 $wgOut->setRobotpolicy( "noindex,nofollow" );
1351 $wgOut->addHTML( wfMsg( "imagereverted" ) );
1352 $wgOut->returnToMain( false );
1353 }
1354
1355 function rollback()
1356 {
1357 global $wgUser, $wgTitle, $wgLang, $wgOut, $from;
1358
1359 if ( ! $wgUser->isSysop() ) {
1360 $wgOut->sysopRequired();
1361 return;
1362 }
1363
1364 # Replace all this user's current edits with the next one down
1365 $tt = wfStrencode( $wgTitle->getDBKey() );
1366 $n = $wgTitle->getNamespace();
1367
1368 # Get the last editor
1369 $sql = "SELECT cur_id,cur_user,cur_user_text,cur_comment FROM cur WHERE cur_title='{$tt}' AND cur_namespace={$n}";
1370 $res = wfQuery( $sql );
1371 if( ($x = wfNumRows( $res )) != 1 ) {
1372 # Something wrong
1373 $wgOut->addHTML( wfMsg( "notanarticle" ) );
1374 return;
1375 }
1376 $s = wfFetchObject( $res );
1377 $ut = wfStrencode( $s->cur_user_text );
1378 $uid = $s->cur_user;
1379 $pid = $s->cur_id;
1380
1381 $from = str_replace( '_', ' ', wfCleanQueryVar( $from ) );
1382 if( $from != $s->cur_user_text ) {
1383 $wgOut->setPageTitle(wfmsg("rollbackfailed"));
1384 $wgOut->addWikiText( wfMsg( "alreadyrolled",
1385 htmlspecialchars( $wgTitle->getPrefixedText()),
1386 htmlspecialchars( $from ),
1387 htmlspecialchars( $s->cur_user_text ) ) );
1388 if($s->cur_comment != "") {
1389 $wgOut->addHTML(
1390 wfMsg("editcomment",
1391 htmlspecialchars( $s->cur_comment ) ) );
1392 }
1393 return;
1394 }
1395
1396 # Get the last edit not by this guy
1397 $sql = "SELECT old_text,old_user,old_user_text
1398 FROM old USE INDEX (name_title_timestamp)
1399 WHERE old_namespace={$n} AND old_title='{$tt}'
1400 AND (old_user <> {$uid} OR old_user_text <> '{$ut}')
1401 ORDER BY inverse_timestamp LIMIT 1";
1402 $res = wfQuery( $sql );
1403 if( wfNumRows( $res ) != 1 ) {
1404 # Something wrong
1405 $wgOut->setPageTitle(wfMsg("rollbackfailed"));
1406 $wgOut->addHTML( wfMsg( "cantrollback" ) );
1407 return;
1408 }
1409 $s = wfFetchObject( $res );
1410
1411 # Save it!
1412 $newcomment = str_replace( "$1", $s->old_user_text, wfMsg( "revertpage" ) );
1413 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
1414 $wgOut->setRobotpolicy( "noindex,nofollow" );
1415 $wgOut->addHTML( "<h2>" . $newcomment . "</h2>\n<hr>\n" );
1416 $this->updateArticle( $s->old_text, $newcomment, 1, $wgTitle->userIsWatching() );
1417
1418 $wgOut->returnToMain( false );
1419 }
1420
1421
1422 # Do standard deferred updates after page view
1423
1424 /* private */ function viewUpdates()
1425 {
1426 global $wgDeferredUpdateList, $wgTitle;
1427
1428 if ( 0 != $this->getID() ) {
1429 $u = new ViewCountUpdate( $this->getID() );
1430 array_push( $wgDeferredUpdateList, $u );
1431 $u = new SiteStatsUpdate( 1, 0, 0 );
1432 array_push( $wgDeferredUpdateList, $u );
1433
1434 $u = new UserTalkUpdate( 0, $wgTitle->getNamespace(),
1435 $wgTitle->getDBkey() );
1436 array_push( $wgDeferredUpdateList, $u );
1437 }
1438 }
1439
1440 # Do standard deferred updates after page edit.
1441 # Every 1000th edit, prune the recent changes table.
1442
1443 /* private */ function editUpdates( $text )
1444 {
1445 global $wgDeferredUpdateList, $wgTitle;
1446
1447 wfSeedRandom();
1448 if ( 0 == mt_rand( 0, 999 ) ) {
1449 $cutoff = wfUnix2Timestamp( time() - ( 7 * 86400 ) );
1450 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1451 wfQuery( $sql );
1452 }
1453 $id = $this->getID();
1454 $title = $wgTitle->getPrefixedDBkey();
1455 $adj = $this->mCountAdjustment;
1456
1457 if ( 0 != $id ) {
1458 $u = new LinksUpdate( $id, $title );
1459 array_push( $wgDeferredUpdateList, $u );
1460 $u = new SiteStatsUpdate( 0, 1, $adj );
1461 array_push( $wgDeferredUpdateList, $u );
1462 $u = new SearchUpdate( $id, $title, $text );
1463 array_push( $wgDeferredUpdateList, $u );
1464
1465 $u = new UserTalkUpdate( 1, $wgTitle->getNamespace(),
1466 $wgTitle->getDBkey() );
1467 array_push( $wgDeferredUpdateList, $u );
1468 }
1469 }
1470
1471 /* private */ function setOldSubtitle()
1472 {
1473 global $wgLang, $wgOut;
1474
1475 $td = $wgLang->timeanddate( $this->mTimestamp, true );
1476 $r = str_replace( "$1", "{$td}", wfMsg( "revisionasof" ) );
1477 $wgOut->setSubtitle( "({$r})" );
1478 }
1479
1480 function blockedIPpage()
1481 {
1482 global $wgOut, $wgUser, $wgLang;
1483
1484 $wgOut->setPageTitle( wfMsg( "blockedtitle" ) );
1485 $wgOut->setRobotpolicy( "noindex,nofollow" );
1486 $wgOut->setArticleFlag( false );
1487
1488 $id = $wgUser->blockedBy();
1489 $reason = $wgUser->blockedFor();
1490
1491 $name = User::whoIs( $id );
1492 $link = "[[" . $wgLang->getNsText( Namespace::getUser() ) .
1493 ":{$name}|{$name}]]";
1494
1495 $text = str_replace( "$1", $link, wfMsg( "blockedtext" ) );
1496 $text = str_replace( "$2", $reason, $text );
1497 $wgOut->addWikiText( $text );
1498 $wgOut->returnToMain( false );
1499 }
1500
1501 # This function is called right before saving the wikitext,
1502 # so we can do things like signatures and links-in-context.
1503
1504 function preSaveTransform( $text )
1505 {
1506 $s = "";
1507 while ( "" != $text ) {
1508 $p = preg_split( "/<\\s*nowiki\\s*>/i", $text, 2 );
1509 $s .= $this->pstPass2( $p[0] );
1510
1511 if ( ( count( $p ) < 2 ) || ( "" == $p[1] ) ) { $text = ""; }
1512 else {
1513 $q = preg_split( "/<\\/\\s*nowiki\\s*>/i", $p[1], 2 );
1514 $s .= "<nowiki>{$q[0]}</nowiki>";
1515 $text = $q[1];
1516 }
1517 }
1518 return rtrim( $s );
1519 }
1520
1521 /* private */ function pstPass2( $text )
1522 {
1523 global $wgUser, $wgLang, $wgTitle, $wgLocaltimezone;
1524
1525 # Signatures
1526 #
1527 $n = $wgUser->getName();
1528 $k = $wgUser->getOption( "nickname" );
1529 if ( "" == $k ) { $k = $n; }
1530 if(isset($wgLocaltimezone)) {
1531 $oldtz = getenv("TZ"); putenv("TZ=$wgLocaltimezone");
1532 }
1533 /* Note: this is an ugly timezone hack for the European wikis */
1534 $d = $wgLang->timeanddate( date( "YmdHis" ), false ) .
1535 " (" . date( "T" ) . ")";
1536 if(isset($wgLocaltimezone)) putenv("TZ=$oldtz");
1537
1538 $text = preg_replace( "/~~~~/", "[[" . $wgLang->getNsText(
1539 Namespace::getUser() ) . ":$n|$k]] $d", $text );
1540 $text = preg_replace( "/~~~/", "[[" . $wgLang->getNsText(
1541 Namespace::getUser() ) . ":$n|$k]]", $text );
1542
1543 # Context links: [[|name]] and [[name (context)|]]
1544 #
1545 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
1546 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
1547 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
1548
1549 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
1550 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
1551 $p3 = "/\[\[([A-Za-z _]+):({$np}+)\\|]]/"; # [[namespace:page|]]
1552 $p4 = "/\[\[([A-Aa-z _]+):({$np}+) \\(({$np}+)\\)\\|]]/";
1553 # [[ns:page (cont)|]]
1554 $context = "";
1555 $t = $wgTitle->getText();
1556 if ( preg_match( $conpat, $t, $m ) ) {
1557 $context = $m[2];
1558 }
1559 $text = preg_replace( $p4, "[[\\1:\\2 (\\3)|\\2]]", $text );
1560 $text = preg_replace( $p1, "[[\\1 (\\2)|\\1]]", $text );
1561 $text = preg_replace( $p3, "[[\\1:\\2|\\2]]", $text );
1562
1563 if ( "" == $context ) {
1564 $text = preg_replace( $p2, "[[\\1]]", $text );
1565 } else {
1566 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
1567 }
1568 # Replace local image links with new [[image:]] style
1569
1570 $text = preg_replace(
1571 "/(^|[^[])http:\/\/(www.|)wikipedia.com\/upload\/" .
1572 "([a-zA-Z0-9_:.~\%\-]+)\.(png|PNG|jpg|JPG|jpeg|JPEG|gif|GIF)/",
1573 "\\1[[image:\\3.\\4]]", $text );
1574 $text = preg_replace(
1575 "/(^|[^[])http:\/\/(www.|)wikipedia.com\/images\/uploads\/" .
1576 "([a-zA-Z0-9_:.~\%\-]+)\.(png|PNG|jpg|JPG|jpeg|JPEG|gif|GIF)/",
1577 "\\1[[image:\\3.\\4]]", $text );
1578
1579 return $text;
1580 }
1581
1582
1583 /* Caching functions */
1584
1585 function tryFileCache() {
1586 if($this->isFileCacheable()) {
1587 if($this->isFileCacheGood()) {
1588 wfDebug( " tryFileCache() - about to load\n" );
1589 $this->loadFromFileCache();
1590 exit;
1591 } else {
1592 wfDebug( " tryFileCache() - starting buffer\n" );
1593 ob_start( array(&$this, 'saveToFileCache' ) );
1594 }
1595 } else {
1596 wfDebug( " tryFileCache() - not cacheable\n" );
1597 }
1598 }
1599
1600 function isFileCacheable() {
1601 global $wgUser, $wgTitle, $wgUseFileCache, $wgShowIPinHeader;
1602 global $action, $oldid, $diff, $redirect, $printable;
1603 return $wgUseFileCache
1604 and (!$wgShowIPinHeader)
1605 and ($wgUser->getId() == 0)
1606 and (!$wgUser->getNewtalk())
1607 and ($wgTitle->getNamespace != Namespace::getSpecial())
1608 and ($action == "view")
1609 and (!isset($oldid))
1610 and (!isset($diff))
1611 and (!isset($redirect))
1612 and (!isset($printable))
1613 and (!$this->mRedirectedFrom);
1614
1615 }
1616
1617 function fileCacheName() {
1618 global $wgTitle, $wgFileCacheDirectory, $wgLang;
1619 if( !$this->mFileCache ) {
1620 $hash = md5( $key = $wgTitle->getDbkey() );
1621 if( $wgTitle->getNamespace() )
1622 $key = $wgLang->getNsText( $wgTitle->getNamespace() ) . ":" . $key;
1623 $key = str_replace( ".", "%2E", urlencode( $key ) );
1624 $hash1 = substr( $hash, 0, 1 );
1625 $hash2 = substr( $hash, 0, 2 );
1626 $this->mFileCache = "{$wgFileCacheDirectory}/{$hash1}/{$hash2}/{$key}.html";
1627 wfDebug( " fileCacheName() - {$this->mFileCache}\n" );
1628 }
1629 return $this->mFileCache;
1630 }
1631
1632 function isFileCacheGood() {
1633 global $wgUser, $wgCacheEpoch;
1634 if(!file_exists( $fn = $this->fileCacheName() ) ) return false;
1635 $cachetime = wfUnix2Timestamp( filemtime( $fn ) );
1636 $good = ( $this->mTouched <= $cachetime ) &&
1637 ($wgCacheEpoch <= $cachetime );
1638 wfDebug(" isFileCacheGood() - cachetime $cachetime, touched {$this->mTouched} epoch {$wgCacheEpoch}, good $good\n");
1639 return $good;
1640 }
1641
1642 function loadFromFileCache() {
1643 global $wgUseGzip;
1644 wfDebug(" loadFromFileCache()\n");
1645 $filename=$this->fileCacheName();
1646 $filenamegz = "{$filename}.gz";
1647 if( $wgUseGzip
1648 && wfClientAcceptsGzip()
1649 && file_exists( $filenamegz)
1650 && ( filemtime( $filenamegz ) >= filemtime( $filename ) ) ) {
1651 wfDebug(" sending gzip\n");
1652 header( "Content-Encoding: gzip" );
1653 header( "Vary: Accept-Encoding" );
1654 $filename = $filenamegz;
1655 }
1656 readfile( $filename );
1657 }
1658
1659 function saveToFileCache( $text ) {
1660 global $wgUseGzip, $wgCompressByDefault;
1661
1662 wfDebug(" saveToFileCache()\n");
1663 $filename=$this->fileCacheName();
1664 $mydir2=substr($filename,0,strrpos($filename,"/")); # subdirectory level 2
1665 $mydir1=substr($mydir2,0,strrpos($mydir2,"/")); # subdirectory level 1
1666 if(!file_exists($mydir1)) { mkdir($mydir1,0777); } # create if necessary
1667 if(!file_exists($mydir2)) { mkdir($mydir2,0777); }
1668 $f = fopen( $filename, "w" );
1669 if($f) {
1670 $now = wfTimestampNow();
1671 fwrite( $f, str_replace( "</html>",
1672 "<!-- Cached $now -->\n</html>",
1673 $text ) );
1674 fclose( $f );
1675 if( $wgUseGzip and $wgCompressByDefault ) {
1676 $start = microtime();
1677 wfDebug(" saving gzip\n");
1678 $gzout = gzencode( str_replace( "</html>",
1679 "<!-- Cached/compressed $now -->\n</html>",
1680 $text ) );
1681 if( $gzout === false ) {
1682 wfDebug(" failed to gzip compress, sending plaintext\n");
1683 return $text;
1684 }
1685 if( $f = fopen( "{$filename}.gz", "w" ) ) {
1686 fwrite( $f, $gzout );
1687 fclose( $f );
1688 $end = microtime();
1689
1690 list($usec1, $sec1) = explode(" ",$start);
1691 list($usec2, $sec2) = explode(" ",$end);
1692 $interval = ((float)$usec2 + (float)$sec2) -
1693 ((float)$usec1 + (float)$sec1);
1694 wfDebug(" saved gzip in $interval\n");
1695 } else {
1696 wfDebug(" failed to write gzip, still sending\n" );
1697 }
1698 if(wfClientAcceptsGzip()) {
1699 header( "Content-Encoding: gzip" );
1700 header( "Vary: Accept-Encoding" );
1701 return $gzout;
1702 }
1703 }
1704 }
1705 return $text;
1706 }
1707
1708 }
1709
1710 ?>